package common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 实现图像操作
 * @author maojj
 *
 */
public class ImageOperation
{
	/**
	 * 对字节数组进行Base64编码
	 * @param bytes - 字节数组
	 * @return 编码后的字符串
	 */
	public static String base64Encode(byte[] bytes)
	{
		return new BASE64Encoder().encode(bytes);
	}
	
	/**
	 * 对图像进行Base64编码
	 * @param imagePath - 图像绝对路径
	 * @return 编码后的字符串
	 * @throws IOException 
	 */
	public static String base64Encode(String imagePath) throws IOException
	{
		byte[] bytes = getBytes(imagePath);
		return new BASE64Encoder().encode(bytes);
	}

	/**
	 * 对Base64编码的图像进行解码
	 * @param base64Image - Base64编码的图像字符串
	 * @return 解码后的字节数组
	 * @throws IOException 
	 */
	public static byte[] base64Decode(String base64Image) throws IOException
	{
		byte[] bytes = null;
		BASE64Decoder decoder = new BASE64Decoder();
		bytes = decoder.decodeBuffer(base64Image);
		return bytes;
	}
	

	/**
	 * 对Base64编码的图像进行解码并生成图像
	 * @param base64Image - Base64编码的图像字符串
	 * @param imagePath - 生成图像的绝对路径
	 * @return 成功返回true，失败返回false
	 * @throws IOException 
	 */
	public static Boolean base64Decode(String base64Image, String imagePath) throws IOException
	{
		//图像数据为空
		if (base64Image == null)
		{
			return false;
		}
		
		//Base64解码
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytes = decoder.decodeBuffer(base64Image);
		//调整异常数据
		for (int i = 0; i < bytes.length; ++i)
		{
			if (bytes[i] < 0)
			{
				bytes[i] += 256;
			}
		}
			
		//生成新图像
		OutputStream out = new FileOutputStream(imagePath);
		out.write(bytes);
		out.flush();
		out.close();
		return true;
	}

	/**
	 * 获得文件的字节数组
	 * @param filePath - 文件绝对路径
	 * @return 文件的字节数组
	 * @throws IOException 
	 */
	public static byte[] getBytes(String filePath) throws IOException
	{  
	    byte[] buffer = null;
	    File file = new File(filePath);
	    FileInputStream fis = new FileInputStream(file);
	    ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
	    byte[] bytes = new byte[1000];
	    int n;
	    while ((n = fis.read(bytes)) != -1)
	    {
	    	bos.write(bytes, 0, n);
	    }
	    fis.close();
	    bos.close();
	    buffer = bos.toByteArray();  
	    return buffer;  
	}

}
